package com.ncmmall.application.business.marketing;

import com.feijin.commons.lang.ArithUtils;
import com.feijin.commons.lang.Requires;
import com.feijin.commons.webs.SyncLock;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCard;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCard;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardOrder;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardOrderRepository;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecord;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecordRepository;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRepository;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;

/**
 * 购物卡订单
 *
 * @author likaikai
 * @date 2020-01-17 19:14:53
 */
@Service
@Transactional
public class ShoppingCardOrderApplication {

    @Autowired
    private ShoppingCardOrderRepository shoppingCardOrderRepository;

    @Autowired
    private ShoppingCardRecordRepository shoppingCardRecordRepository;

    @Autowired
    private ShoppingCardRepository shoppingCardRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 购物卡订单取消支付
     *
     * @param order 订单
     */
    public void cancel(ShoppingCardOrder order) {

        order.setStatus(3);
        shoppingCardOrderRepository.save(order);

        ShoppingCard card = order.getShoppingCard();
        synchronized (SyncLock.getLock(String.valueOf(card.getId()))) {
            card = queryChannelService.findOne(QShoppingCard.shoppingCard.id.eq(order.getShoppingCard().getId()), ShoppingCard.class);
            card.setSaleNumberCount(Math.max(card.getSaleNumberCount() - 1, 0));
            shoppingCardRepository.save(card);
        }

    }

    /**
     * 创建购物卡订单
     *
     * @param orderNo 订单号
     * @param member  购买人
     * @param card    购物卡
     */
    public ShoppingCardOrder createOrder(String orderNo, WebUser member, ShoppingCard card) {

        synchronized (SyncLock.getLock(String.valueOf(card.getId()))) {
            card = queryChannelService.findOne(QShoppingCard.shoppingCard.id.eq(card.getId()), ShoppingCard.class);
            Requires.isTrue(card.getNumber() > card.getSaleNumberCount(), "购物卡库存不足");
            card.setSaleNumberCount(card.getSaleNumberCount() + 1);
            shoppingCardRepository.save(card);
        }

        ShoppingCardOrder order = new ShoppingCardOrder();
        order.setUser(member);
        order.setOrderNo(orderNo);
        order.setPrice(card.getPrice());
        order.setCreateTime(new Timestamp(System.currentTimeMillis()));
        order.setStatus(1);
        order.setShoppingCard(card);
        shoppingCardOrderRepository.save(order);

        return order;


    }

    /**
     * 自动取消过时订单
     */
    public void autoCancelOrders() {

        List<ShoppingCardOrder> orders = queryChannelService.queryAllEntity("select * from mall_shopping_card_order where status = 1 AND TIMESTAMPDIFF(minute, createTime, NOW()) > 5", Collections.emptyMap(), ShoppingCardOrder.class);

        for (ShoppingCardOrder order : orders) {
            order.setStatus(3);

            synchronized (SyncLock.getLock(String.valueOf(order.getShoppingCard().getId()))) {
                ShoppingCard card = queryChannelService.findOne(QShoppingCard.shoppingCard.id.eq(order.getShoppingCard().getId()), ShoppingCard.class);
                card.setSaleNumberCount(card.getSaleNumberCount() - 1);
                shoppingCardRepository.save(card);
            }
        }
        shoppingCardOrderRepository.save(orders);
    }

    /**
     * 购物卡订单支付成功
     *
     * @param order 订单
     */
    public void wechatPaySuccess(ShoppingCardOrder order) {

        //保存订单
        order.setStatus(2);
        order.setPayTime(new Timestamp(System.currentTimeMillis()));
        shoppingCardOrderRepository.save(order);

        //保存购物卡销售数量，销售价格
        ShoppingCard shoppingCard = order.getShoppingCard();
        shoppingCard.setSalePriceCount(ArithUtils.add(shoppingCard.getSalePriceCount(), order.getPrice()));
        shoppingCardRepository.save(shoppingCard);

        //生成用户购物卡记录
        ShoppingCardRecord record = new ShoppingCardRecord();
        record.setCreateTime(order.getPayTime());
        record.setShoppingCard(order.getShoppingCard());
        record.setSource(1);
        record.setUser(order.getUser());
        record.setStatus(1);
        record.setBalance(shoppingCard.getFaceValue());

        if (shoppingCard.getValidType() == 1) {
            record.setValidStartTime(shoppingCard.getValidStartTime());
            record.setValidEndTime(shoppingCard.getValidEndTime());
        } else {
            record.setValidStartTime(order.getPayTime());
            Timestamp endTime = new Timestamp(order.getPayTime().getTime() + (long) shoppingCard.getValidDays() * 24 * 3600 * 1000);
            record.setValidEndTime(endTime);
        }
        shoppingCardRecordRepository.save(record);
    }
}
